package net.lainiao.mycost.controller;

import net.lainiao.mycost.bean.ExpenseAccount;
import net.lainiao.mycost.bean.UserInfo;
import net.lainiao.mycost.utils.Page;
import net.lainiao.mycost.utils.ProcessUtils;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by Administrator on 2017/3/22.
 */
@Controller
@RequestMapping("/expa/")
public class ExpenseActivitConterller extends Page {
    @Autowired
    private ProcessEngine processEngine;

    @RequestMapping("loadadd.do")
    public String loadadd() {
        return "expa/expa_add";
    }

    @RequestMapping("add.do")
    public String add(HttpSession session, ExpenseAccount account, Model model) {
        ProcessInstance pi = processEngine.getRuntimeService().startProcessInstanceByKey(ProcessUtils.PROCESS_DEFINITON_EKY);
        String processIntanceId = pi.getProcessInstanceId();
        TaskService taskService = processEngine.getTaskService();
        Task task = taskService.createTaskQuery().taskAssignee(ProcessUtils.PROCESS_ASSIGNEE_USER).processDefinitionId(processIntanceId).singleResult();
        UserInfo userInfo = (UserInfo) session.getAttribute("user");
        if (account != null) {
            account.setUserId(userInfo.getUserId());
            account.setUserName(userInfo.getUserName());
        }
        taskService.setVariable(task.getId(), ProcessUtils.VARIABLE_NAME, account);
        taskService.complete(task.getId());
        model.addAttribute("info", "报销单提交成功");
        return "expa/expa_add";
    }

    @RequestMapping("list.do")
    public String list(String type, Model model) {
        String assignee = type;
        List<Task> tlist = processEngine.getTaskService().createTaskQuery().taskAssignee(assignee).list();
        TaskService taskService = processEngine.getTaskService();
        if (tlist != null && tlist.size() > 0) {
            List<Map> list = new ArrayList<>();
            for (Task task : tlist) {
                Map map = new HashMap();
                map.put("taskId", task.getId());
                map.put("createTime", task.getCreateTime());
                ExpenseAccount account = (ExpenseAccount) taskService.getVariable(task.getId(), ProcessUtils.VARIABLE_NAME);
                map.put(ProcessUtils.VARIABLE_NAME, account);
                list.add(map);
            }
            model.addAttribute("list", list);
        }
        if (ProcessUtils.PROCESS_ASSIGNEE_MANAGER.equals(assignee)) {
            assignee = "经理审核";
        } else if (ProcessUtils.PROCESS_ASSIGNEE_FINANCE.equals(assignee)) {
            assignee = "财务审核";
        }
        model.addAttribute("assignee", assignee);
        model.addAttribute("type", type);
        return "expa/expa_list";
    }

    @RequestMapping("mylist.do")
    public String mylist(HttpSession session, Model model) {
        UserInfo userInfo = (UserInfo) session.getAttribute("user");
        List<Task> taskList = processEngine.getTaskService().createTaskQuery().taskAssignee(ProcessUtils.PROCESS_ASSIGNEE_USER).list();
        TaskService taskService = processEngine.getTaskService();
        if (taskList != null && taskList.size() > 0) {
            List<Map> list = new ArrayList<>();
            for (Task task : taskList) {
                Map map = new HashMap();
                map.put("taskId", task.getId());
                map.put("createTime", task.getCreateTime());
                ExpenseAccount account = (ExpenseAccount) taskService.getVariable(task.getId(), ProcessUtils.VARIABLE_NAME);
                map.put(ProcessUtils.VARIABLE_NAME, account);
                if (userInfo.getUserId().equals(account.getUserId())) {
                    list.add(map);
                }
            }
            model.addAttribute("list", list);
        }
        return "expa/expa_mylist";
    }

    @RequestMapping("loadManager.do")
    public String loadManager(String taskId, Date createTime, Model model) {
        TaskService taskService = processEngine.getTaskService();
        ExpenseAccount account = (ExpenseAccount) taskService.getVariable(taskId, ProcessUtils.VARIABLE_NAME);
        model.addAttribute("expa", account);
        model.addAttribute("taskId", taskId);
        model.addAttribute("createTime", createTime);
        return "expa/expa_manager_audit";
    }

    @RequestMapping("managerAudit.do")
    public String managerAudit(HttpSession session, String taskId, ExpenseAccount account, Model model) {
        UserInfo userInfo = (UserInfo) session.getAttribute("user");
        System.out.println(taskId);
        TaskService taskService = processEngine.getTaskService();
        ExpenseAccount expenseAccount = (ExpenseAccount) taskService.getVariable(taskId, ProcessUtils.VARIABLE_NAME);
        System.out.println("11111:" + expenseAccount);
        if (expenseAccount != null) {
            expenseAccount.setManagerMark(account.getManagerMark());
            expenseAccount.setManagerDesc(account.getManagerDesc());
            expenseAccount.setManagerId(account.getManagerId());
            expenseAccount.setManagerName(account.getManagerName());
        }
        taskService.setVariable(taskId, ProcessUtils.VARIABLE_NAME, expenseAccount);
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("managerMark", account.getManagerMark());
        taskService.complete(taskId, stringObjectMap);
        model.addAttribute("info", "经理审批完毕");
        return list(ProcessUtils.PROCESS_ASSIGNEE_MANAGER, model);
    }

    @RequestMapping("loadmyExpa.do")
    public String loadMyExpa(String taskId, Date createTime, Model model) {
        TaskService taskService = processEngine.getTaskService();
        ExpenseAccount account = (ExpenseAccount) taskService.getVariable(taskId, ProcessUtils.VARIABLE_NAME);
        model.addAttribute("expa", account);
        model.addAttribute("taskId", taskId);
        model.addAttribute("createTime", createTime);
        return "expa/expa_myadd";
    }

    @RequestMapping("readd.do")
    public String readd(HttpSession session, String taskId, ExpenseAccount account, Model model) {
        TaskService taskService = processEngine.getTaskService();
        UserInfo userInfo = (UserInfo) session.getAttribute("user");
        if (account != null) {
            account.setUserName(userInfo.getUserName());
            account.setUserId(userInfo.getUserId());
        }
        taskService.setVariable(taskId, ProcessUtils.VARIABLE_NAME, account);
        taskService.complete(taskId);
        model.addAttribute("info", "请假单提交成功");
        return mylist(session, model);
    }

    @RequestMapping("loadFinance.do")
    public String loadFinance(String taskId, Date createTime, Model model) {
        TaskService taskService = processEngine.getTaskService();
        ExpenseAccount expenseAccount = (ExpenseAccount) taskService.getVariable(taskId, ProcessUtils.VARIABLE_NAME);
        model.addAttribute("expa", expenseAccount);
        model.addAttribute("taskId", taskId);
        model.addAttribute("createTime", createTime);
        return "expa/expa_finance_audit";
    }

    @RequestMapping("finanaceAudit.do")
    public String financeAudit(HttpSession session, String taskId, ExpenseAccount account, Model model) {
        UserInfo userInfo = (UserInfo) session.getAttribute("user");
        TaskService taskService = processEngine.getTaskService();
        ExpenseAccount expenseAccount = (ExpenseAccount) taskService.getVariable(taskId, ProcessUtils.VARIABLE_NAME);
        if (expenseAccount != null) {
            expenseAccount.setFinnaceId(userInfo.getUserId());
            expenseAccount.setFinanceName(userInfo.getUserName());
            expenseAccount.setFinanceMark(account.getFinanceMark());
            expenseAccount.setFinanceDesc(account.getFinanceDesc());
        }
        taskService.setVariable(taskId, ProcessUtils.VARIABLE_NAME, expenseAccount);
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("financeMark", account.getFinanceMark());
        taskService.complete(taskId, stringObjectMap);
        model.addAttribute("info", "财务审批完毕!");
        return list(ProcessUtils.PROCESS_ASSIGNEE_FINANCE, model);
    }

    @RequestMapping("hisList.do")
    public String hisList(Model model) {
        List<HistoricProcessInstance> list = processEngine.getHistoryService().createHistoricProcessInstanceQuery().processDefinitionKey(ProcessUtils.PROCESS_DEFINITON_EKY).orderByProcessInstanceStartTime().desc().list();
        if (list != null && list.size() > 0) {
            List<Map> tlist = new ArrayList<>();
            for (HistoricProcessInstance processInstance : list) {
                Map map = new HashMap();
                map.put("processInstanceId", processInstance.getId());
                map.put("processDefinitionId", processInstance.getProcessDefinitionId());
                map.put("startTime", processInstance.getStartTime());
                map.put("endTime", processInstance.getEndTime());
                if (processInstance.getEndTime() != null) {
                    map.put("mark", "1");
                } else {
                    map.put("mark", "2");
                }
                List<HistoricVariableInstance> hvlist = processEngine.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).list();
                if (hvlist != null) {
                    for (HistoricVariableInstance hvi : hvlist) {
                        map.put(hvi.getVariableName(), hvi.getValue());
                    }
                }
                tlist.add(map);
            }
        }
        return "expa/expa_his_list";
    }

    @RequestMapping("hisMyList.do")
    public String hisMyList(HttpSession session, Model model) {
        List<HistoricProcessInstance> list = processEngine.getHistoryService().createHistoricProcessInstanceQuery().processDefinitionKey(ProcessUtils.PROCESS_DEFINITON_EKY).orderByProcessInstanceStartTime().desc().list();
        if (list != null && list.size() > 0) {
            List<Map> tlist = new ArrayList<>();
            for (HistoricProcessInstance hpi : list) {
                Map map = new HashMap();
                map.put("processInstanceId", hpi.getId());
                map.put("processDefinitionId", hpi.getProcessDefinitionId());
                map.put("startTime", hpi.getStartTime());
                map.put("endTime", hpi.getEndTime());
                if (hpi.getEndTime() != null) {
                    map.put("mark", "1");
                } else {
                    map.put("mark", "2");
                }
                UserInfo userInfo = (UserInfo) session.getAttribute("user");
                List<HistoricVariableInstance> hvList = processEngine.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(hpi.getId()).list();
                if (hvList != null) {
                    for (HistoricVariableInstance hvi : hvList) {
                        if (hvi.getVariableName().equals(ProcessUtils.VARIABLE_NAME)) {
                            ExpenseAccount account = (ExpenseAccount) hvi.getValue();
                            if (userInfo.getUserId().equals(account.getUserId())) {
                                map.put(hvi.getVariableName(), hvi.getValue());
                                tlist.add(map);
                            }
                        }
                    }
                }
            }
            model.addAttribute("tlist", tlist);
        }
        return "expa/expa_his_my_list";
    }

    @RequestMapping("showImg.do")
    public String showImg(String processDefinitionId, String processInstanceId, Model model) {
        ActivityImpl activity = null;
        activity = ProcessUtils.getProcessMap(processDefinitionId, processInstanceId);
        model.addAttribute("actimpl", activity);
        model.addAttribute("processDefinitionId", processDefinitionId);
        return "expa/expa_img";
    }

    @RequestMapping("findImg.do")
    public void findImg(String processDefinitionId, HttpServletResponse response) throws IOException {
        InputStream inputStream = ProcessUtils.findProcessImg(processDefinitionId);
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(buf, 0, 1024)) != -1) {
            response.getOutputStream().write(buf, 0, buf.length);
        }
        inputStream.close();
    }
}

